//
//  MapManager.swift
//  ltsp
//
//  Created by jyvyi_ios on 2022/6/17.
//

import Foundation
#if canImport(MapKit)
import MapKit
/*
 1.使用此功能需要 添加库MapKit.framework
 2.打开地图功能
 */
enum MapSearchType : String,CaseIterable{
    case placeNames = "Place names"
    case cafe   //咖啡厅
    case supermarket  //超市
    case village  //乡村
    case Community
    case Shop  //商店
    case Restaurant  //饭馆
    case School  //学校
    case hospital //医院
    case Company  //公司
    case Street //街道
    case ConvenienceStore = "Convenience store" //便利超市
    case ShoppingCentre = "Shopping Centre"  //购物中心
    case Hotel  //酒店
    case GroceryStore = "Grocery store" //
    
    case all //所有
}

protocol MapManager_h{
    
    /// 获取特定经纬度周边的关键词的坐标集
    /// - Parameters:
    ///   - centerCoordinate: 中心经纬度
    ///   - latitudinalMeters: 纬度上的距离
    ///   - longitudinalMeters: 经度上的距离
    ///   - keyword: 关键字
    ///   - successedBlock: 成功回调
    ///   - failureBlock: 失败回调
    func searchNearby(of centerCoordinate:CLLocationCoordinate2D , latitudinalMeters:CLLocationDistance ,longitudinalMeters:CLLocationDistance ,searchKey:String,successedBlock:@escaping ReturnValueBlock<MKLocalSearch.Response?>,failureBlock:ReturnValueBlock<Error>?)
    
    /// 取消搜索
    func cancelSearch()
}
class MapManager : MapManager_h{
    
    var search : MKLocalSearch?
    
    func searchNearby(of centerCoordinate:CLLocationCoordinate2D , latitudinalMeters:CLLocationDistance ,longitudinalMeters:CLLocationDistance ,searchKey:String,successedBlock:@escaping ReturnValueBlock<MKLocalSearch.Response?>,failureBlock:ReturnValueBlock<Error>?){
        
        let region : MKCoordinateRegion = MKCoordinateRegion.init(center: centerCoordinate, latitudinalMeters: latitudinalMeters, longitudinalMeters: longitudinalMeters)
        let request = MKLocalSearch.Request()
        request.region = region
        request.naturalLanguageQuery = searchKey
        let localSearch = MKLocalSearch.init(request: request)
        localSearch.start { response, error in
            
            if error != nil{
                failureBlock?(error!)
            }
            else{
                successedBlock(response)
            }
        }
        self.search = localSearch
    }
    
    func cancelSearch(){
        
        self.search?.cancel()
    }
    fileprivate class func searchKeyword(for types:[MapSearchType]) -> String{
        
        var searchTypes = types
        if searchTypes.contains(.all){
            searchTypes = MapSearchType.allCases
        }
        
        var keywords : [String] = []
        for searchType in searchTypes {
            guard searchType != .all else {
                continue
            }
            keywords.append(searchType.rawValue)
        }
        let keyword = keywords.joined(separator: ",")
        print(keyword)
        return keyword
    }
}
#endif
